<template>
	<view class="u-wrap">
		<!-- header start -->
		<view class="header">
			<view v-if="subCurrent">
				<view class="header__title">{{shopDetail.address}}</view>
				<view class="header__info">
					<text class="header__name">{{shopDetail.shopName}}</text>
					<text>{{shopDetail.phone.substring(0,3)}} **** {{shopDetail.phone.substring(9,11)}}</text>
				</view>
			</view>
			<view v-else>
				<view class="header__title">{{shopDetail.address}}</view>
				<view class="header__info">距离您{{shopDetail.distance.toFixed(2)}}km</view>
			</view>
			<view>
				<u-subsection v-if="shopDetail.subCurrent==2" :list="subList" :current="subCurrent"
					active-color="#EE2F37" mode="subsection" height="50" :bold="false"
					@change="subChange"></u-subsection>
			</view>
		</view>
		<!-- header end -->

		<!-- menu start -->
		<view class="u-menu-wrap">
			<scroll-view scroll-y scroll-with-animation class="u-tab-view menu-scroll-view" :scroll-top="scrollTop"
				:show-scrollbar="false" enhanced>
				<view v-for="item in tabbar" :key="item.id" class="u-tab-item"
					:class="[current.id==item.id ? 'u-tab-item-active' : '']" :data-current="item.id"
					@tap.stop="swichMenu(item)">
					<u-image :src="item.icon" width="60" height="60" class="menuimg"></u-image>
					<text class="tabMenu-name">{{item.name}}</text>
				</view>
				<u-gap height="300" bg-color="#FFFFFF"></u-gap>
			</scroll-view>
			<block>
				<scroll-view scroll-y class="right-box" :show-scrollbar="false" enhanced>
					<view class="right-box__swiper">
						<u-swiper :list="bannerList" @click="clickBanner()" :height="180"></u-swiper>
					</view>
					<view class="page-view">
						<view class="item-title">
							<text>{{current.name}}</text>
						</view>
						<view class="class-item">
							<view class="class-item-box" v-for="(item1, index1) in foods" :key="index1">
								<image class="item-menu-image" @click="showProductDetailModal(item1)"
									:src="item1.imageUrl" mode="aspectFill"></image>
								<view class="item-menu-name">
									<text class="item-menu-name__name"
										@click="showProductDetailModal(item1)">{{item1.name}}</text>
									<view class="item-menu-name__desc u-line-2" @click="showProductDetailModal(item1)">
										{{item1.description}}
									</view>
									<view class="item-menu-price">
										<view class="item-menu-price__color">
											<text class="item-menu-price__text">￥</text>
											{{item1.price}}
										</view>
										<view>
											<view v-if="item1.specs.length>0 && item1.value == 0" class="specs"
												@click="showProductDetailModal(item1)">选规格
											</view>
											<u-number-box v-else :min="0" :max="100" disabled-input
												v-model="item1.value" :long-press="false" color="#fff"
												@plus="plusMenu(item1)" @minus="minusMenu(item1)"></u-number-box>
										</view>
									</view>
								</view>
							</view>
						</view>
					</view>
					<u-gap height="200" bg-color="#FAFAFA"></u-gap>
				</scroll-view>
			</block>
		</view>
		<!-- menu end -->

		<!-- bottom start-->
		<view class="u-bottom">
			<view class="u-bottom__wrap" @click="MenuPopup">
				<view class="u-bottom__bags">
					<u-badge :count="menuNum" type="error" :offset="[-5,-10]"></u-badge>
					<u-icon name="/static/menu/bags.png" size="50"></u-icon>
				</view>
				<view class="u-bottom__price">
					<text>￥</text>
					{{(Math.abs(menuPrice) === 0 ? '0.00' : menuPrice.toFixed(2))}}
				</view>
				<view class="u-bottom__nums">共 {{menuNum}} 件商品</view>
			</view>
			<view class="u-bottom__place" :class="{'u-bottom__place--disabled': menuPrice <= 0}" @click="settlement">
				{{goPlace}}
			</view>
		</view>
		<!-- bottom start -->

		<!-- popup start -->
		<u-popup v-model="PopupShow" mode="bottom" height="70%" border-radius="14">
			<view class="popup-wrap">
				<!-- clearshoppingCar -->
				<view class="emptyShop" @click="clickEmptyShop">
					<u-icon name="trash" class="emptyShop__icon"></u-icon>清空购物车
				</view>
				<u-gap height="80"></u-gap>
				<!-- menulist -->
				<view class="menulist" v-for="(item, index) in SelectMenu" :key="index">
					<image class="item-menu-images" :src="item.imageUrl" mode="aspectFill"></image>
					<view class="item-menu-name">
						<text class="item-menu-name__name">{{item.name}}</text>
						<view class="item-menu-name__desc">
							{{item.description}}
						</view>
						<view class="item-menu-name__specs">
							<view class="spec" v-for="(it,dex) in item.productSpecs" :key="dex">
								{{dex == 0 ? '':'-'}}{{it.option}}
							</view>
						</view>
						<view class="item-menu-price">
							<view class="item-menu-price__color">
								<text class="item-menu-price__text">￥</text>{{item.price}}
							</view>
							<view>
								<u-number-box :min="0" :max="100" disabled-input v-model="item.value"
									:long-press="false" color="#fff" @plus="plusMenu(item)"
									@minus="minusMenu(item)"></u-number-box>
							</view>
						</view>
					</view>
				</view>
			</view>
		</u-popup>
		<!-- popup end -->
		<productModal :product="prodcutData" :visible="productModalVisible" @cancel="closeProductDetailModal"
			@add-to-cart="handleAddToCartInModal"></productModal>
	</view>
</template>

<script>
	import {
		doGetLocation
	} from '@/common/getLocation.js'
	import {
		mapState
	} from "vuex";
	import menuList from '@/common/menu.js';
	import {
		getCategoryList,
		getProducts,
		getShoppingCartLists,
		updateShoppingCart,
		delShoppingCart,
		getBannerList,
		getShopDetail,
	} from "@/request/API.js";
	import productModal from "@/pages/menu/comment/product-modal/product-modal.vue"
	export default {
		components: {
			productModal
		},
		computed: {
			...mapState(['shopDetail', 'subCurrent', 'shopId'])
		},
		data() {
			return {
				PopupShow: false,
				tabbar: [],
				scrollTop: 0,
				current: 0,
				menuHeight: 0,
				menuItemHeight: 0,
				menuNum: 0,
				goPlace: "去结算",
				menuPrice: 0,
				prodcutData: {},
				productModalVisible: false,
				SelectMenu: [],
				foods: [],
				subList: [{
						name: '堂食'
					},
					{
						name: '外卖'
					}
				],
				bannerList: [],
				bannerData: [],
				selfAddress: {
					lon: '', // 经度
					lat: '', // 纬度
				},
			}
		},
		async created() {
			let that = this;
			await doGetLocation(async (data) => {
				that.$store.commit('setSelfAddress', data);
				const detail = await getShopDetail({
					id: this.shopId,
					longitude: data.longitude,
					latitude: data.latitude
				});
				that.$store.commit('setShopDetail', detail.data);
			});
		},
		async onLoad() {
			let {
				data
			} = await getCategoryList({
				id: 1
			});
			this.tabbar = data;
			this.swichMenu(data[0]);
			this.getBanner();
		},
		watch: {
			menuNum() {
				this.setGoPlace()
			},
			subCurrent() {
				this.setGoPlace()
			}
		},
		methods: {
			clickBanner(index) {
				console.log("当前点击了广告图，数据为：", this.bannerData[index]);
			},
			async getBanner() {
				const {
					data
				} = await getBannerList({
					id: 1
				});
				data.sort((a, b) => a.sort - b.sort);
				let that = this;
				data.forEach(item => {
					that.bannerList.unshift(item.imageUrl)
				})
				this.bannerData = data;
			},
			async setShoppingCart() {
				let {
					data
				} = await getShoppingCartLists({
					shopId: uni.getStorageSync("shop_id")
				});
				let that = this;
				let menuNum = 0;
				let menuPrice = 0;
				// 初始化获取购物车信息
				data.forEach(item => {
					item.value = item.number;
					item.productSpecs = (item.productSpecs != null && item.productSpecs !== "") ? JSON
						.parse(item.productSpecs) : "";
					item.price = Number(item.amount);
					menuNum += Number(item.number);
					menuPrice += Number(item.amount) * Number(item.number);
					/* that.foods.map(it => {
						if (it.id == item.id) {
							it.value = item.number;
						}
					}) */
				});
				that.foods.map(item => {
					let d = data.find(it => it.id == item.id);
					if (d != null && d != '') {
						item.value = d.number;
					} else {
						item.value = 0;
					}
				})
				this.menuPrice = menuPrice;
				this.menuNum = menuNum;
				this.SelectMenu = data;
			},
			showProductDetailModal(product) {
				let list = {
					id: product.id,
					name: product.name,
					price: product.price,
					number: 1,
					description: product.description,
					imageUrl: product.imageUrl,
					amount: product.price,
					materials: []
				}
				if (product.specs && Array.isArray(product.specs)) {
					// 初始化 materials 数组（如果尚未存在）
					list.materials = list.materials || [];
					product.specs.forEach(({
						specName,
						options
					}) => {
						const material = {
							group_name: specName,
							values: options.map(({
								optionValue,
								isSelected,
								price
							}) => ({
								name: optionValue,
								is_selected: isSelected,
								price
							}))
						};

						list.materials.push(material);
					});
				}
				this.prodcutData = list;
				this.productModalVisible = true
			},
			closeProductDetailModal() {
				this.productModalVisible = false
				this.product = {}
			},
			handleAddToCartInModal(product) {
				let list = {
					id: product.id,
					imageUrl: product.imageUrl,
					name: product.name,
					value: product.number,
					description: product.description,
					price: product.amount,
					// specs: product.materials,
					specs: product.spec
				}
				// 添加到购物车
				this.plusMenu(list);
				this.closeProductDetailModal();
			},
			// ubsection
			subChange(param) {
				this.$store.commit('setSubCurrent', param);
				uni.setStorageSync('setSubCurrent', param);
			},
			async updateShopping(product) {
				await updateShoppingCart({
					number: product.value,
					shopId: uni.getStorageSync("shop_id"),
					productId: product.id,
					productSpecs: (product.specs != null && product.specs !== "") ? JSON.stringify(product
						.specs) : "",
					amount: product.price
				});
				this.setShoppingCart();
			},
			// addvariety为何向/user/shopping/update接口发送数据时，请求头必须携带content-type: application/x-www-form-urlencoded否则无法接收到携带的参数
			plusMenu(param) {
				console.log("当前为plusMenu：", param);
				this.updateShopping(param);

			},
			// deletevariety
			minusMenu(param) {
				console.log("minusMenu");
				this.updateShopping(param);
			},
			// goSettle
			settlement() {
				if (this.menuNum != 0 && this.menuPrice != 0) {
					if (this.subCurrent != 0 && this.menuPrice - this.shopDetail.minDeliveryPrice < 0) {
						return;
					} else {
						// init
						this.SelectMenu = this.SelectMenu.filter(item => item.value !== 0);
						let key = {
							order: this.SelectMenu,
							menuPrice: this.menuPrice,
							menuNum: this.menuNum
						}
						uni.setStorage({
							key: 'dishData',
							data: key,
							success: () => {
								uni.navigateTo({
									url: "/subPack/index/indexSettlement"
								})
							}
						});
					}

				}
			},
			// clearshoppingCar
			async clickEmptyShop() {
				// menuNuminit
				/* this.SelectMenu.forEach(food => {
					food.value = 0;
				}); 
				this.menuNum = 0;
				this.menuPrice = 0;
				*/
				await delShoppingCart(uni.getStorageSync("shop_id"));
				this.foods.forEach(item => {
					item.value = 0;
				})
				//init
				this.SelectMenu = [];
				this.PopupShow = false;
				this.setShoppingCart();
			},
			// popup
			MenuPopup() {
				if (this.menuNum != 0 && this.menuPrice != 0) {
					this.PopupShow = true;
					// init
					this.SelectMenu = this.SelectMenu.filter(item => item.value !== 0);
				}
			},
			// clickLstMenuTabs
			async swichMenu(item) {
				if (item.id == this.current.id) return;
				this.current = item;
				let {
					data
				} = await getProducts(item.id);
				data.forEach(item => {
					item.value = 0
				})
				this.foods = data;
				this.setShoppingCart();
			},
			getElRect(elClass, dataVal) {
				new Promise((resolve, reject) => {
					const query = uni.createSelectorQuery().in(this);
					query.select('.' + elClass).fields({
						size: true
					}, res => {
						if (!res) {
							setTimeout(() => {
								this.getElRect(elClass);
							}, 10);
							return;
						}
						this[dataVal] = res.height;
					}).exec();
				})
			},
			setGoPlace() {
				let price = this.menuPrice - this.shopDetail.minDeliveryPrice;
				if (price < 0 && this.subCurrent != 0) {
					this.goPlace = `差￥${Math.abs(price.toFixed(2))}起送`
				} else {
					this.goPlace = '去结算'
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	.specs {
		width: 100rpx;
		height: 50rpx;
		text-align: center;
		line-height: 50rpx;
		font-size: 24rpx;
		border-radius: 40rpx;
		color: #FFFFFF;
		background-color: #EE2F37;
	}

	.u-wrap {
		height: calc(100vh);
		/* #ifdef H5 */
		height: calc(100vh - var(--window-top));
		/* #endif */
		display: flex;
		flex-direction: column;
	}

	.header {
		display: flex;
		justify-content: space-between;
		padding: 30rpx;

		&__title {
			font-weight: bold;
		}

		&__info {
			font-size: 24rpx;
			color: $u-type-info;
			margin-top: 15rpx;
		}

		&__name {
			margin-right: 15rpx;
		}
	}

	.menuimg {
		margin-bottom: 10rpx;
	}

	.logo {
		margin: -80rpx 0 15rpx 50rpx;

		image {
			width: 120rpx;
			height: 120rpx;
			border-radius: 50%;
			border: 20rpx solid #fff;
		}
	}

	.u-menu-wrap {
		flex: 1;
		display: flex;
		overflow: hidden;
	}

	.u-tab-view {
		width: 200rpx;
		height: 100%;
		background-color: #FFFFFF;
	}

	.tabMenu-name {
		text-align: center;
		padding: 0 10rpx;
	}

	.u-bottom__place--disabled {

		background-color: #c8c9cc !important;

		pointer-events: none;

		cursor: not-allowed;

	}

	.u-tab-item {
		height: 160rpx;
		background: #FFFFFF;
		box-sizing: border-box;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		font-size: 22rpx;
		font-weight: 600;
		color: #8D9699;
		font-weight: 400;
		line-height: 1;
	}

	.u-tab-item-active {
		position: relative;
		color: #EE2F37;
		font-size: 22rpx;
		font-weight: 600;
		background: #FAFAFA;
	}

	.u-tab-item-active::before {
		content: "";
		position: absolute;
		border-left: 2px solid #EE2F37;
		height: 160rpx;
		left: 0;
		top: 0;
	}

	.u-tab-view {
		height: 100%;
	}

	.right-box {
		background-color: #FAFAFA;

		&__swiper {
			margin: 0 30rpx;
		}
	}

	.item-title {
		font-size: 22rpx;
		color: $u-main-color;
		font-weight: bold;
		padding: 16rpx 16rpx 0 16rpx;
	}

	.page-view {
		padding: 16rpx;
	}

	.class-item {
		margin-bottom: 30rpx;
		padding: 16rpx;
		border-radius: 8rpx;
	}

	.class-item-box {
		display: flex;
		background-color: white;
		padding: 20rpx;
		margin-bottom: 20rpx;
		box-shadow: 2px 0px 8px 0px rgba(244, 244, 245, 0.75);
		border-radius: 14rpx;
	}

	.item-menu-name {
		display: flex;
		flex-direction: column;
		margin-left: 20rpx;
		width: 100%;

		&__name {
			font-weight: bold;
			font-size: 30rpx;
		}

		&__desc {
			margin: 20rpx 0;
			font-size: 20rpx;
			color: $u-type-info;
		}
	}

	.item-menu-price {
		display: flex;
		justify-content: space-between;

		&__color {
			font-weight: bold;
			font-size: 36rpx;
			color: #EE2F37;
		}

		&__text {
			font-size: 22rpx;
		}
	}

	.item-menu-image {
		width: 50%;
		height: 160rpx;
		border-radius: 20rpx;
	}

	.item-menu-images {
		width: 30%;
		height: 150rpx;
		border-radius: 20rpx;
	}

	.u-bottom {
		position: fixed;
		z-index: 777;
		/* #ifdef MP-WEIXIN */
		bottom: 30rpx;
		/* #endif */
		/* #ifdef H5 */
		bottom: 130rpx;
		/* #endif */
		width: 92%;
		left: 0;
		right: 0;
		margin: 0 auto;
		display: flex;
		box-shadow: 2px 0px 8px 0px rgba(200, 201, 204, 0.75);
		border-radius: 14rpx;
		background-color: white;

		&__bags {
			position: relative;
			// display: flex;
			// flex-direction: column;
			// justify-content: space-around;
			// border: 1px solid #f00;
		}

		&__price {
			font-weight: bold;
			font-size: 40rpx;
			margin-left: 20rpx;

			text {
				font-size: 24rpx;
			}
		}

		&__nums {
			border-left: 1px solid #303133;
			font-size: 24rpx;
			margin-left: 20rpx;
			padding-left: 20rpx;
			font-weight: bold;
		}

		&__wrap,
		&__place {
			display: flex;
			color: #303133;
		}

		&__wrap {
			width: 70%;
			padding: 20rpx 0 20rpx 30rpx;
			align-items: center;
		}

		&__place {
			background-color: #EE2F37;
			width: 30%;
			text-align: center;
			flex-direction: column;
			justify-content: center;
			font-size: 32rpx;
			font-weight: bold;
			color: white;
			border-top-right-radius: 14rpx;
			border-bottom-right-radius: 14rpx;
		}
	}

	.popup-wrap {
		margin: 20rpx 30rpx 0 30rpx;
		padding-bottom: 30rpx;
	}

	.emptyShop {
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
		background-color: #fff;
		color: $u-type-info;
		font-size: 24rpx;
		border-bottom: 1px solid #f3f4f6;
		z-index: 2;
		padding: 20rpx;
		display: flex;
		justify-content: flex-end;

		&__icon {
			margin-right: 20rpx;
		}
	}

	.item-menu-name__specs {
		margin: 0;
		font-size: 20rpx;
		color: #8D9699;
	}

	.menulist {
		display: flex;
		margin-bottom: 30rpx;
	}
</style>